package com.mf.all.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mf.all.exception.GraceException;
import com.mf.all.service.ServiceRolePermission;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.mf.all.entity.dto.DtoPermission;
import com.mf.all.entity.req.search.user.SearchReqPermission;
import com.mf.all.mapper.MapperPermission;
import com.mf.all.service.ServicePermission;

import java.util.ArrayList;
import java.util.List;


@Service
public class ImplServicePermission extends ServiceImpl<MapperPermission, DtoPermission> implements ServicePermission {
    @Resource
    private ServiceRolePermission serviceRolePermission;


    @Override
    public LambdaQueryWrapper<DtoPermission> fillParams(SearchReqPermission params) {
        final LambdaQueryWrapper<DtoPermission> wrapper = loadQw();
        wrapper.eq(ObjectUtils.isNotEmpty(params.getPid()), DtoPermission::getPid, params.getPid());
        if (StringUtils.isNotBlank(params.getKey())) {
            wrapper.and(w -> {
                w.like(DtoPermission::getPermName, params.getKey())
                        .or()
                        .like(DtoPermission::getRemark, params.getKey())
                        .or()
                        .like(DtoPermission::getCode, params.getKey());
            });
        }
        return wrapper;
    }

    /**
     * 根据用户id查询权限
     */
    @Override
    public List<DtoPermission> listByUserId(long userId) {
        return baseMapper.listByUserId(userId);
    }

    /**
     * 删除权限
     */
    @Override
    public void deleteById(Integer id) {
        if (serviceRolePermission.isBindRole(id)) {
            GraceException.display("当前权限有绑定角色无法删除");
        }
        this.removeById(id);
    }

    /**
     * 验证是否存在子节点
     */
    @Override
    public void validateId(Integer id) {
        if (ObjectUtils.isNotEmpty(id)) {
            final DtoPermission permission = baseMapper.selectById(id);
            if (ObjectUtils.isEmpty(permission)) {
                GraceException.display("当前父级不存在");
            }
        }
    }

    /**
     * 查询所有权限(树结构)
     */
    @Override
    public List<DtoPermission> permissionByTree() {
        final List<DtoPermission> permissionList = list();
        // 顶层权限节点
        final List<DtoPermission> permissions = permissionList.stream().filter(p -> p.getPid() == 0).toList();
        for (DtoPermission permission : permissions) {
            permission.setChildren(getChild(permission.getId(), permissionList, permission.getChildren()));
        }
        return permissions;
    }

    /**
     * 根据角色id查询权限
     */
    @Override
    public List<DtoPermission> permissionByRoleId(Integer roleId) {

        return baseMapper.permissionByRoleId(roleId);
    }

    /**
     * 递归获取子节点
     */
    private List<DtoPermission> getChild(Integer id, List<DtoPermission> allPermissions, List<DtoPermission> children) {
        if (children == null) {
            children = new ArrayList<>();
        }


        for (DtoPermission allPermission : allPermissions) {
            if (allPermission.getPid().equals(id)) {
                children.add(allPermission);
            }
        }
        if (!children.isEmpty()) {
            for (DtoPermission child : children) {
                child.setChildren(getChild(child.getId(), allPermissions, child.getChildren()));
            }
        }
        return children;
    }
}